package com.xuecheng.manage_course.service;

import com.xuecheng.framework.domain.course.Category;
import com.xuecheng.framework.domain.course.CourseBase;
import com.xuecheng.framework.domain.course.response.AddCourseResult;
import com.xuecheng.framework.domain.system.SysDictionary;
import com.xuecheng.framework.domain.system.SysDictionaryValue;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.dao.CategoryRepository;
import com.xuecheng.manage_course.dao.CourseBaseRepository;
import com.xuecheng.manage_course.feign.cms.SysDictionaryFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 课程Service
 */
@Service
public class CourseBaseService {
    @Value("${xuecheng.dictionary_url}")
    private String dictionary_url;
    @Value("${xuecheng.course_grade_type}")
    private String course_grade_type;
    @Value("${xuecheng.course_studymodel_type}")
    private String course_studymodel_type;
    @Resource
    CourseBaseRepository courseBaseRepository;
    @Resource
    CategoryRepository categoryRepository;
    @Resource
    SysDictionaryFeign sysDictionaryFeign;

    /**
     * 添加一个课程基本信息
     *
     * @param courseBase 课程信息
     * @return 添加成功的响应
     */
    public AddCourseResult addCourseBase(CourseBase courseBase) {
        // 校验大分类是否存在
        Optional<Category> mt = categoryRepository.findById(courseBase.getMt());
        if (!mt.isPresent()) {
            return new AddCourseResult(CommonCode.INVALID_JSON_PARAMETER, "");
        }
        // 校验小分类是否存在
        Optional<Category> st = categoryRepository.findById(courseBase.getSt());
        if (!st.isPresent()) {
            return new AddCourseResult(CommonCode.INVALID_JSON_PARAMETER, "");
        }
        // 远程调用检查课程等级是否合法
        try {
            boolean flag = this.checkSysDictionary(courseBase);
            if (flag){
                // 增加课程默认的状态为   新课程发布
                courseBase.setStatus("202001");
                // 添加课程中的数据字典合法,添加数据
                CourseBase save = courseBaseRepository.save(courseBase);
                return new AddCourseResult(CommonCode.SUCCESS, save.getId());
            } else {
                // 不在就不合法
                return new AddCourseResult(CommonCode.INVALID_JSON_PARAMETER, "");
            }
        } catch (Exception e) {
            // 远程调用http://www.xuecheng.com:31001/sys/dictionary/get/失败
            return new AddCourseResult(CommonCode.SERVER_ERROR, "");
        }
    }

    /**
     * 根据课程id查询一个课程信息
     *
     * @param courseId 课程id
     * @return 发货查出来的实体类
     */
    public CourseBase getCourseBaseById(String courseId) {
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        return optional.orElse(null);
    }

    /**
     * 修改课程信息
     *
     * @param courseId   课程id
     * @param courseBase 课程实体类
     * @return 响应结果
     */
    public ResponseResult updateCoursebase(String courseId, CourseBase courseBase) {
        // 查询课程信息是否存在
        CourseBase courseBaseById = this.getCourseBaseById(courseId);
        if (courseBaseById == null) {
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
        // 校验大分类信息合法性
        Optional<Category> mt = categoryRepository.findById(courseBase.getMt());
        // 校验小分类是否存在
        Optional<Category> st = categoryRepository.findById(courseBase.getSt());
        if (mt.isPresent() && st.isPresent()){
            // 查询数据字典的合法性
            try{
                boolean flag = this.checkSysDictionary(courseBase);
                if (flag){
                    courseBase.setId(courseId);
                    courseBaseRepository.save(courseBase);
                    return new ResponseResult(CommonCode.SUCCESS);
                }else {
                    return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
                }
            }catch (Exception e){
                return new ResponseResult(CommonCode.SERVER_ERROR);
            }
        }else {
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
    }

    /**
     * 根据dictionary_url 和  course_grade_type 查询数据字典信息 并且校验实体类中数据字典数据是否合法
     * @param courseBase 需要校验的实体类
     * @return 校验成功返回true,失败返回false
     */
    public boolean checkSysDictionary(CourseBase courseBase) throws Exception{
        SysDictionary gradeEntity = sysDictionaryFeign.findSysDictionaryByType(course_grade_type);
        SysDictionary studymodelEntity = sysDictionaryFeign.findSysDictionaryByType(course_studymodel_type);
        List<SysDictionaryValue> gradeEntityDValue = gradeEntity.getDValue();
        List<SysDictionaryValue> studymodelEntityDValue = studymodelEntity.getDValue();
        if (gradeEntityDValue.size() == 0 || studymodelEntityDValue.size() == 0){
            return false;
        }else {
            SysDictionaryValue grade = gradeEntityDValue.stream().filter(e -> e.getSdId().equals(courseBase.getGrade())).findFirst().orElse(null);
            SysDictionaryValue study = studymodelEntityDValue.stream().filter(e -> e.getSdId().equals(courseBase.getStudymodel())).findFirst().orElse(null);
            if (grade ==null || study==null){
                return false;
            }else {
                return true;
            }
        }
    }
}
